<template>
  <div
    class="com_container"
    style="position: relative;"
  >
    <div class="drop">
      <el-dropdown
        trigger="click"
        @command="handleCommand"
      >
        <span class="el-dropdown-link">
          ▎{{showTitle}}<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="item in selectTypes"
            :key="item.key"
            :command="item.key"
          >{{item.text}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div
      class="com_eachrt"
      ref="echart"
    >
    </div>
  </div>
</template>

<script>
import { getAction } from '@/api/manage';
import '@/assets/echart/theme/chalk';
export default {
  data() {
    return {
      //echartInstance实例类
      chartInstance: null,
      //数据集合
      dataList: null,
      // 显示的数据类型
      choiceType: 'map',
      //标题字体大小
      titleFontSize: '',
    };
  },
  mounted() {
    this.initEchart();
    this.getData();
    //设置监听事件，监听窗口大小动态改变echart的大小（注意销毁）
    window.addEventListener('resize', this.screenAdapter);
    // 在页面加载完成的时候, 主动进行屏幕的适配
    this.screenAdapter();
  },
  computed: {
    //计算下拉选
    selectTypes() {
      if (!this.dataList) {
        return [];
      }
      return this.dataList.type.filter((item) => {
        return item.key !== this.choiceType;
      });
    },
    //计算标题
    showTitle() {
      if (!this.dataList) {
        return '';
      } else {
        return this.dataList[this.choiceType].title;
      }
    },
  },
  methods: {
    //初始化echart
    initEchart() {
      //初始化echart对象，并指明主题
      this.chartInstance = this.$echarts.init(this.$refs.echart, 'chalk');
      const initOption = {
        //坐标轴举例设置
        grid: {
          left: '3%',
          top: '35%',
          right: '4%',
          bottom: '1%',
          containLabel: true,
        },
        //鼠标悬浮，工具内容提示
        tooltip: {
          trigger: 'axis',
        },
        //设置[图例]样式（位置在左边，圆形）
        legend: {
          left: 20,
          top: '15%',
          icon: 'circle',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false, //折线与坐标轴设置没有间隙
        },
        yAxis: {
          type: 'value',
        },
      };
      this.chartInstance.setOption(initOption);
    },
    //获取服务器数据
    async getData() {
      const { data: resArr } = await getAction('/echart/getJson', {
        fileName: 'trend.json',
      });
      this.dataList = resArr;
      //更新echart
      this.updateChart();
    },
    //更新echart
    updateChart() {
      // 半透明的颜色值
      const colorArr1 = [
        'rgba(11, 168, 44, 0.5)',
        'rgba(44, 110, 255, 0.5)',
        'rgba(22, 242, 217, 0.5)',
        'rgba(254, 33, 30, 0.5)',
        'rgba(250, 105, 0, 0.5)',
      ];
      // 全透明的颜色值
      const colorArr2 = [
        'rgba(11, 168, 44, 0)',
        'rgba(44, 110, 255, 0)',
        'rgba(22, 242, 217, 0)',
        'rgba(254, 33, 30, 0)',
        'rgba(250, 105, 0, 0)',
      ];
      // 类目轴的数据
      const timeArr = this.dataList.common.month;
      // y轴数据 series下的数据
      const valueArr = this.dataList[this.choiceType].data;
      const seriesArr = valueArr.map((item, index) => {
        return {
          name: item.name,
          type: 'line',
          stack: 'all', //数据堆叠（或者使用toolbox-feature-magicType-type:stack来实现效果）
          data: item.data,
          //区域显示
          areaStyle: {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: colorArr1[index],
              }, // %0的颜色值
              {
                offset: 1,
                color: colorArr2[index],
              }, // 100%的颜色值
            ]),
          },
        };
      });
      // 图例的数据 (注意：series必须有name)
      const legendArr = valueArr.map((item) => {
        return item.name;
      });
      const dataOption = {
        xAxis: {
          data: timeArr,
        },
        legend: {
          data: legendArr,
        },
        series: seriesArr,
      };
      this.chartInstance.setOption(dataOption);
    },
    // 当浏览器的大小发生变化的时候, 会调用的方法, 来完成屏幕的适配
    screenAdapter() {
      // 和分辨率大小相关的配置项
      this.titleFontSize = (this.$refs.echart.offsetWidth / 100) * 3.6;
      console.log('titleFontSize', this.titleFontSize);
      const adapterOption = {
        legend: {
          itemWidth: this.titleFontSize,
          itemHeight: this.titleFontSize,
          itemGap: this.titleFontSize,
          textStyle: {
            fontSize: this.titleFontSize / 2,
          },
        },
      };
      this.chartInstance.setOption(adapterOption);
      // 手动的调用图表对象的resize 才能产生效果
      this.chartInstance.resize();
    },
    //选择当前所展示
    handleCommand(currentType) {
      this.choiceType = currentType;
      this.updateChart();
    },
  },
  destroyed() {
    //销毁监听事件
    window.removeEventListener('resize', this.screenAdapter);
  },
};
</script>

<style lang="scss" scoped>
.drop {
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 10;
  .el-dropdown-link {
    cursor: pointer; //鼠标悬浮变小手
  }
  .el-dropdown {
    font-size: 24px;
    color: white;
  }
}
</style>